/*+********************************************************
Filename: main.c
Description: simple led&button control example.
  Run on TangPrimer20kDock FPGA based self-defined MCU
  peripheral with SparrowRV core.

Modification:
2024.05.05 creation H.Zheng
********************************************************-*/


//peripheral memory map
#define GPIO_ODR      *((volatile unsigned int *)0x10000000)
#define GPIO_IDR      *((volatile unsigned int *)0x10000004)
#define UART_TXD      *((volatile unsigned int *)0x10000040)
#define UART_RXD      *((volatile unsigned int *)0x10000040)
#define UART_STATUS   *((volatile unsigned int *)0x10000044)
#define TIMER_CTRL    *((volatile unsigned int *)0x10000080)
#define TIMER_COUNTER *((volatile unsigned int *)0x10000084)
#define TIMER_TOP     *((volatile unsigned int *)0x10000088)
//
int buttonPushed(){
    unsigned int i, button;
    i = GPIO_IDR&0x07;
    if (i== 0x07)
        return 0;
    else if ((i&0x01)== 0)
        button=1;
    else if ((i&0x02)== 0)
        button= 2;
    else if ((i&0x04)== 0)
        button= 3;
    else
        button = 0;
    //wait for button released
    while ((GPIO_IDR&0x07)!= 0x07) {
    }
    //
    return button;
}

int main(){
    unsigned int button;

    GPIO_ODR = 0x1;
    while (1){
        button = buttonPushed();

        //action based on pushed button
        switch (button) {
        case 1:
            GPIO_ODR = GPIO_ODR + 1;
            break;
        case 2:
            GPIO_ODR = GPIO_ODR - 1;
            break;
        case 3:
            GPIO_ODR = 0;
            break;
        }
    }
}
